package org.xqh.test.ugreen;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.arronlong.httpclientutil.HttpClientUtil;
import com.arronlong.httpclientutil.common.HttpConfig;
import com.arronlong.httpclientutil.common.HttpHeader;
import com.arronlong.httpclientutil.common.HttpMethods;
import com.arronlong.httpclientutil.common.HttpResult;
import com.arronlong.httpclientutil.exception.HttpProcessException;
import com.google.common.collect.Lists;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.Header;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.xqh.utils.file.ReadTxtFileUtils;
import org.xqh.utils.http.FxHttpClientUtils;

import java.io.File;
import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @ClassName GitLabDelete
 * @Description 删除 gitlab 分支/标签
 * @Author xuqianghui
 * @Date 2023/12/1 13:21
 * @Version 1.0
 */
@Slf4j
public class GitLabDelete {

    private final static String query_branch_url = "http://192.168.24.24:8080/cloud/%s/-/branches/all?page=%s";

    private final static String del_branch_url = "http://192.168.24.24:8080/cloud/%s/-/branches/%s";

    private final static String del_tag_url = "http://192.168.24.24:8080/cloud/%s/-/tags/%s";

    private final static String query_tag_url = "http://192.168.24.24:8080/cloud/%s/-/tags?page=%s&sort=updated_desc";

    private final static String gitlab_token = "ksvHaDxHyiReMG2sOSnrkqHDAWILFUq9VnDYqz+YI+bUg+pkvMox3IX4rDtn90O8CcaMSrry3WS0Cbj9YvnSUg==";
    private final static String gitlab_cookie = "sidebar_collapsed=false; event_filter=all; _gitlab_session=2fa1767898b414a46b48a3dd69b84105";


    public static void main(String[] args) {
        String jsonStr = ReadTxtFileUtils.readJson(new File("D:\\test\\重复数据.txt"));
        JSONObject data = JSON.parseObject(jsonStr);
        JSONArray jsonArray = data.getJSONArray("data");
        Map<String, Boolean> checkMap = new HashMap<>();
        Map<String, AtomicInteger> count = new HashMap<>();
        for(Object obj:jsonArray){
            JSONObject json = (JSONObject) obj;
            String appId = json.getString("appId");
            JSONObject version = json.getJSONObject("version");
            Boolean gray = version.getBoolean("gray");
            String url = json.getString("url");//按断是否是有效的 元素
            String checkKey = String.format("%s-%s", appId, gray);
            if(StringUtils.hasText(url)){
                checkMap.put(checkKey, true);
            }
            if(count.containsKey(checkKey)){
                count.get(checkKey).incrementAndGet();
            }else {
                count.put(checkKey, new AtomicInteger(1));
            }
        }

        System.out.println(JSON.toJSONString(count));

        List<JSONObject> delList = Lists.newArrayList();
        JSONArray result = new JSONArray();
        Set<String> resultSet = new HashSet<>();
        for(Object obj:jsonArray){
            JSONObject json = (JSONObject) obj;
            String appId = json.getString("appId");
            JSONObject version = json.getJSONObject("version");
            Boolean gray = version.getBoolean("gray");
            String url = json.getString("url");//按断是否是有效的 元素
            String checkKey = String.format("%s-%s", appId, gray);
            if(StringUtils.hasText(url) && checkMap.containsKey(checkKey) && !resultSet.contains(checkKey)){
                result.add(json);
                resultSet.add(checkKey);
            }
        }
        System.out.println(JSON.toJSONString(result));

    }
    public static void main222(String[] args) throws HttpProcessException {
        String serviceName = "ugreen_nas_admin";
        deleteBranchByBranchList(Lists.newArrayList(
                "feature/2310/experience_update_admin",
                "feature/2310/device_black_list_time_1027",
                "feature/pro2310/sda_middle_bug_fix",
                "feature/2310/experience_update_admin_tcm_1020",
                "feature/202306/help_center",
                "feature/pro2310/application_client_upgrade",
                "feature/2310/upload_file_oss_1013",
                "feature/2309/meizu_wallpaper_config",
                "feature/pro2310/help_center_type_query",
                "feature/pro2310/automatic_log_out_tcm_1009",
                "feature/pro2310/automatic_log_out_tcm",
                "feature/2310/upd_p2p_storage_sdk",
                "feature/2309/zen_tao_bug_count",
                "feature/application-center-pro",
                "feature/oauth-2.0-xqh-0725",
                "feature/pro2308/admin_db_split",
                "feature/2309/fw_version_Identifier",
                "feature/2309/device_cache_optimize",
                "feature/2309/fwVer-multi-model",
                "feature/2309/experience_account",
                "feature/pro2309/upk_json_to_db",
                "hotfix/operational_data_0822",
                "feature/pro2306/device_db_split",
                "feature/2308/operational_data",
                "feature/2308/add_tunnel_ip",
                "feature/2308/sms_template_dync_config",
                "feature/2308/upgrade_notice_check",
                "feature/2308/feed_back_collect",
                "feature/2308/wallpaper_mgr",
                "feature/pro2307/data_center",
                "feature/202306/p2p_authorize_code_type_0626"
        ), serviceName);
//        deleteTagsByParams("2.2.9.1", serviceName);//删除 该标签之前的所有标签
//        deleteTagsByTagList(Lists.newArrayList("pro-1.0.0",
//                "pro-1.0.0.1",
//                "pro-1.0.0.2",
//                "pro-1.0.0.3",
//                "pro-1.0.0.4",
//                "pro-1.0.0.5",
//                "pro-1.0.0.6",
//                "pro-1.0.0.7",
//                "pro-1.0.0.8",
//                "pro-1.0.0.9",
//                "pro-1.0.0.10"
//        ), "ugreen-service-system");
//        List<String> branches = queryAllBranches(serviceName);
//        System.out.println(JSON.toJSONString(branches));
    }

    public static void deleteTagsByTagList(List<String> tagList, String serviceName){
        for(String tag:tagList){
            deleteTag(tag, serviceName);
        }
    }

    public static void deleteBranchByBranchList(List<String> branchList, String serviceName){
        for(String branch:branchList){
            deleteBranch(branch, serviceName);
        }
    }

    private static void deleteBranch(String branch, String serviceName) {
        log.info("delete branch ===>: {}", branch);
        String reqUrl = String.format(del_branch_url, serviceName, branch);
        requestGitlab(reqUrl, HttpMethods.DELETE);
    }

    public static void deleteTagsByParams(String limitTag, String serviceName) {
        List<String> tags = queryAllTags(serviceName);
        System.out.println(JSON.toJSONString(tags));
        if (!tags.contains(limitTag)) {
            return;
        }
        for (int i = tags.size() - 1; i >= 0; i--) {
            String tag = tags.get(i);
            if (limitTag.equalsIgnoreCase(tag)) {
                break;
            }
            deleteTag(tag, serviceName);
        }
    }

    /**
     * 拉取所有的分支
     * @return
     */
    public static List<String> queryAllBranches(String serviceName){
        List<String> result = Lists.newArrayList();
        int i = 1;
        while (true) {
            String url = String.format(query_branch_url, serviceName, i);
            String html = requestGitlab(url, HttpMethods.GET);
            List<String> items = regexBranchNameList(html);
            if (CollectionUtils.isEmpty(items)) {
                break;
            }
            result.addAll(items);
            i++;
        }
        return result;
    }


    /**
     * 拉取所有的tag
     * @return
     */
    public static List<String> queryAllTags(String serviceName) {
        List<String> result = Lists.newArrayList();
        int i = 1;
        while (true) {
            String url = String.format(query_tag_url, serviceName, i);
            String html = requestGitlab(url, HttpMethods.GET);
            List<String> items = regexTagNameList(html);
            if (CollectionUtils.isEmpty(items)) {
                break;
            }
            result.addAll(items);
            i++;
        }
        return result;
    }

    public static List<String> regexBranchNameList(String html) {
        String regex = "qa-branch-name.*>(.*)(</a>|\n</a>)";
        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher(html);
        List<String> result = Lists.newArrayList();
        while (matcher.find()) {
            String branch = matcher.group(1);
            if (!result.contains(branch)) {
                result.add(branch);
            }
        }
        return result;
    }

    public static List<String> regexTagNameList(String html) {
        String regex = "((pro-|>)[0-9,.]+)</a>";
        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher(html);
        List<String> result = Lists.newArrayList();
        while (matcher.find()) {
            String tag = matcher.group(1);
            if (tag.startsWith(">")) {
                tag = tag.substring(1);
            }
            if (!result.contains(tag) && tag.contains(".")) {
                result.add(tag);
            }
        }
        return result;
    }

    /**
     * 删除标签
     *
     * @param tag
     * @throws HttpProcessException
     */
    public static void deleteTag(String tag, String serviceName){
        log.info("delete tag ===>: {}", tag);
        String reqUrl = String.format(del_tag_url, serviceName, tag);
        requestGitlab(reqUrl, HttpMethods.DELETE);
    }

    public static String requestGitlab(String url, HttpMethods method) {
        HttpConfig config = FxHttpClientUtils.getHttpConfig(url);
        config.method(method);
        config.headers(getHeaders());
        try {
            HttpResult result = HttpClientUtil.sendAndGetResp(config);
            return result.getResult();
        } catch (Exception e) {
            log.error("", e);
        }
        return null;
    }

    public static Header[] getHeaders() {
        Header[] headers = HttpHeader.custom()
                .other("X-Csrf-Token", gitlab_token)
                .other("Cookie", gitlab_cookie)
                .build();
        return headers;
    }
}
